<template>
  <div class="upload-container">
    <el-button icon="el-icon-upload" size="mini" type="primary" @click="dialogVisible = true">
      上传
    </el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        :http-request="httpRequest"
        class="editor-slide-upload"
        action="#"
        list-type="picture-card"
      >
        <el-button size="small" type="primary"> 点击上传 </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getOss } from '@/utils/alioss'
import { setUpFileName } from '@/hooks'
export default {
  name: 'EditorSlideUpload',
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: []
    }
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        return
      }
      this.$emit('successCBK', arr)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    async httpRequest(file) {
      // 得到文件的内容
      let fileArray = []
      fileArray.push(file.file)

      let uploadImage = async file => {
        console.log(file)
        //填写获取签名的地址
        const policyData = await getOss()
        let ossUrl = 'https://oss.wasaiyouxuan.com' //填写自己OSS服务器的地址
        let accessUrl = policyData.objPath + '/' + setUpFileName(file) //设置上传的访问路径
        let sendData = new FormData() // 上传文件的data参数

        // form提交
        sendData.append('OSSAccessKeyId', 'LTAI5tATQrBDh3vWLfLAxgHT')
        sendData.append('policy', policyData.policy)
        sendData.append('Signature', policyData.signature)
        sendData.append('bucketName', policyData.bucketName)
        sendData.append('key', accessUrl)
        sendData.append('objPath', policyData.objPath)
        sendData.append('success_action_status', 200)
        sendData.append('file', file)

        await axios.post(ossUrl, sendData)
        return `${ossUrl}/${accessUrl}`
      }

      // 循环上传
      fileArray.forEach(file => {
        uploadImage(file).then(data => {
          this.uploading = false
          if (this.isShowSuccessTip) {
            this.$message.success('上传成功')
          }
          const uid = file.uid
          const objKeyArr = Object.keys(this.listObj)
          for (let i = 0, len = objKeyArr.length; i < len; i++) {
            if (this.listObj[objKeyArr[i]].uid === uid) {
              this.listObj[objKeyArr[i]].url = data
              this.listObj[objKeyArr[i]].hasSuccess = true
              return
            }
          }
        })
      })
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function () {
          _self.listObj[fileName] = {
            hasSuccess: false,
            uid: file.uid,
            width: this.width,
            height: this.height
          }
        }
        resolve(true)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  ::v-deep .el-upload--picture-card {
    width: 100%;
  }
}
</style>
